define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        user_models = require('js/apps/console/models'),
        utils = require('js/utils/tools'),
        tz = require('js/utils/tz'),
        cookie = require('js/utils/cookie'),
        app = Backbone.history;
    require('datetimepicker');
    require('multiselect');
    require('magnific');
    require('jquery-ui');
    
    var CouponListView = Backbone.View.extend({
        events: {
            'click #search': 'doSearch',
            'change #selectAll': 'selectAll',
            'change .check-row': 'checkRow',
            'click #payCloseBtn': 'closePayDialog',
            'click #paySaveBtn': 'savePayDialog'
        },
        initialize: function (options) {
            this.options = options;
            this.collection = new models.CouponCollection();
            this.user_collection = new user_models.UserCollection();
            this.checkedIds = [];
            this.collection.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        closePayDialog: function () {
            $("#payDialog").hide();
        },
        savePayDialog: function () {
            const that = this;
            let dataArray = [];
            if ($("input[name='justpay_alipay']").is( ":checked" )) {
                dataArray.push($("input[name='justpay_alipay']").val())
            }
            if ($("input[name='group_alipay']").is( ":checked" )) {
                dataArray.push($("input[name='group_alipay']").val())
            }
            if ($("input[name='unionagency_bankcard']").is( ":checked" )) {
                dataArray.push($("input[name='unionagency_bankcard']").val())
            }
            $.ajax({
                url: '/admin/withdraw/set_available_channels/',
                type: 'POST',
                headers: {
                    'X-AUTH-USER': cookie.getCookie('bigbang_user_id'),
                    'X-AUTH-TOKEN': cookie.getCookie('bigbang_user_token')
                },
                data: JSON.stringify({
                    'channels': dataArray
                })
            }).done(function (resp) {
                notify.success('提示', '刷新成功！');
                that.closePayDialog();
            }).fail(function (resp) {
                notify.error('错误', '刷新失败！');
                console.log(JSON.stringify(resp));
                consoel.log('錯誤', resp);
                that.closePayDialog();
            });
        },
        checkRow: function (e) {
            let tr = $(e.target).closest('tr'),
                id = tr.data('id');
            if ($(e.target).is(':checked')) {
                this.checkedIds.push(id);
            } else {
                this.checkedIds = _.without(this.checkedIds, id);
            }
            $('#selectTips').html('已选中' + this.checkedIds.length + '个');
        },
        _getSearchOption: function () {
            let options = {};
            let searched = utils.getAllInput('#sidebar_right');
            searched.user_id = $('#searchUid').val();
            searched.coupon_type = parseInt($('#searchCouponType').val());
            searched.status = parseInt($('#searchCouponStatus').val());
            searched.source = $('#searchCouponSource').val();

            if (searched.effect_time) {
              options.effect_time = searched.effect_time;
            }
            if (searched.use_time) {
              options.use_time = searched.use_time;
            }

            if (searched.user_id != -1) {
              options.user_id = searched.user_id;
            }
            if (searched.coupon_type != -1) {
              options.coupon_type = searched.coupon_type;
            }
            if (searched.status != -1) {
              options.status = searched.status;
            }
            if (searched.source != -1) {
              options.source = searched.source;
            }

            utils.saveSearched('op/coupon', searched);
            return options;
        },
        doSearch: function () {
            let options = this._getSearchOption();
            options.$page = 1;
            options.$size = 300;
            options._ = new Date().getTime();
            app.navigate(utils.composeQueryString('#op/coupon/', options), {
                trigger: true
            });
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                unuse_count: this.collection.unuse_count,
                unuse_price: this.collection.unuse_price,
                used_count: this.collection.used_count,
                used_price: this.collection.used_price,
                expire_count: this.collection.expire_count,
                expire_price: this.collection.expire_price,
                searched: utils.getSearched('op/coupon')
            }));
            let user_dict = {};
            _.each(this.user_collection.toJSON(), function (k) {
                user_dict[k.id] = k.nickname;
            });
            user_dict[-1] = '系统自动操作';
            let that = this;
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    let newUrl = utils.composeQueryString('#op/coupon/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            $('.datetime-input').datetimepicker({
                format: 'YYYY-MM-DD HH:mm:ss',
            });
            $('.date-input').datetimepicker({
                format: 'YYYY-MM-DD',
            });
            utils.getPaginator(that.options, this.collection.total, '#op/coupon/');
            return this;
        },
        load: function () {
            let that = this;
            this.user_collection.fetch({
                reset: true,
                data: {'disable_paginate': 1},
                success: function () {
                    that.collection.fetch({
                        reset: true,
                        data: that.options,
                        error: function (c, r, o) {
                            notify.notifyResp(r);
                            $('#content').append('<h4 class="text-muted">无数据</h4>');
                        },
                    });
                },
                error: function (c, r, o) {
                    notify.notifyResp(r);
                }
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/Coupon.html",
        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            this.options.$size = 10;
            let view = new CouponListView(this.options);
            view.template = this.template;
            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });
    
});
